package com.qf.smsplatform.strategy.strategy.impl;

import com.qf.smsplatform.common.constants.CacheConstants;
import com.qf.smsplatform.common.constants.StrategyConstants;
import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.strategy.client.CacheClient;
import com.qf.smsplatform.strategy.strategy.Strategy;
import com.qf.smsplatform.strategy.util.PushErrorMessageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 扣费策略
 * @author zjw
 */
@Service(value = "fee")
@Slf4j
public class FeeStrategyImpl implements Strategy {

    @Autowired
    private CacheClient cacheClient;

    @Override
    public boolean execute(StandardSubmit submit) {
        log.info("【策略模块-扣费策略】  开始执行~~~~~~~~~~~~");
        int clientID = submit.getClientID();
        //1. 查询当前短信需要的费用
        long fee = submit.getFee();

        //2. 直接调用CacheClient的hincr命令，获得到扣除费用后的剩余金额
        Long remainFee = cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + clientID,"fee",-fee);

        //3. 判断剩余金额是否小于0，证明用户剩余金额不足
        if(remainFee < 0){
            //4. 把之前预扣除的费用再加回去
            cacheClient.hincr(CacheConstants.CACHE_PREFIX_CLIENT + clientID,"fee",fee);
            //5. 发送消息，返回false
            // 5.1 发送日志
            PushErrorMessageUtil.sendLog(submit, StrategyConstants.STRATEGY_ERROR_FEE);
            // 5.2 状态报告
            Integer isreturnstatus = Integer.valueOf(cacheClient.hget(CacheConstants.CACHE_PREFIX_CLIENT + submit.getClientID(), "isreturnstatus"));
            if(isreturnstatus == 1) {
                PushErrorMessageUtil.sendReport(submit, StrategyConstants.STRATEGY_ERROR_FEE);
            }
            log.info("【策略模块-扣费策略】  执行失败~~~~~~~~~~~~~~~~~~");
            return false;
        }

        // 策略模块无法确定短信是否发送成功，到了网关模块才能确定消息是否发送成功
        log.info("【策略模块-扣费策略】  执行成功！！！！！！");
        return true;
    }
}
